/* ====================================================================
 * (#)Header: ExceptionInterceptor.java
 * (#)Revision: 
 * (#)Date Created: 2009-06-03
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.service.ejb.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.karolak.service.exception.ServiceException;

/**
 * 
 * <code>ExceptionInterceptor</code> is ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class ExceptionInterceptor {

	protected final Log log = LogFactory.getLog(getClass());

	@AroundInvoke
	public Object log(InvocationContext inv) throws Exception {
		Object result = null;
		try {
			result = inv.proceed();
		} catch (ServiceException se) {
			String invMsg = InterceptorUtils.getMessageBeforeInvokation(inv);
			log.error(invMsg, se);
			throw se;
		} catch (Exception e) {
			String invMsg = InterceptorUtils.getMessageBeforeInvokation(inv);
			log.error(invMsg, e);
			throw translateException(e, invMsg);
		}
		return result;
	}

	protected ServiceException translateException(Throwable t, String invMsg) throws Exception {
		Throwable e = t;
		while (true) {
			Throwable cause = e.getCause();
			if (cause instanceof ServiceException) {
				return (ServiceException) cause;
			}
			if (cause == null || cause == e || cause.getClass().equals(e.getClass())) {
				break;
			} else {
				e = cause;
			}
		}
		ServiceException se = new ServiceException(e.getMessage(), invMsg);
		se.setStackTrace(e.getStackTrace());
		return se;
	}
}
